<script setup lang="ts">
import { TypeUserFormI } from '@/api/user/user_types'
import * as roleApi from '@/api/role/role_api_index'
import * as userApi from '@/api/user/user_api_index';
import * as deptApi from '@/api/dept/dept_api_index';
import { ElMessage, FormInstance } from 'element-plus'
import {$bus} from '@/event_bus/event_bus_index'
import { cloneDeep } from 'lodash'
import { reactive, ref } from 'vue'
import EnumElSelectIndex from '@/components/enum_el_select/enum_el_select_index.vue';
import {EnumTypeLable} from '@/types/global/enums/enums_types'
// const props = defineProps({
//     dialogVisible: {
//         type: Boolean,
//         required: true,
//     },
// })
// const emits = defineEmits([ 'update:dialogVisible'])
// const dialogVisible = useVModel(props, 'dialogVisible', emits)

const dialog = reactive({
    visible: false,
    title: '用户信息新增/更新',
    width: 800,
})

// async function openDialog(userId: string | undefined) {
//     //await initForm(userId)
//     dialog.visible = true
//     nextTick(async () => {
//         //await initForm(userId)
//     })
// }

const roleList = ref<TypeOptionI[]>([])

const deptList = ref<TypeOptionI[]>([])

let userId: string | undefined

// 用户表单数据
let formData = ref<TypeUserFormI>({
    status: 1,
    gender: {value:undefined},
})
const formDataIntial: TypeUserFormI = {
    status: 1,
    gender: {value:undefined},
}

console.log('JSON.stringify(formDataIntial) = ', JSON.stringify(formDataIntial))
const userFormRef = ref<FormInstance>() // 用户表单
// 校验规则
const rules = reactive({
    username: [{ required: true, message: '用户名不能为空', trigger: 'blur' }],
    nickname: [{ required: true, message: '用户昵称不能为空', trigger: 'blur' }],
    deptId: [{ required: true, message: '所属部门不能为空', trigger: 'blur' }],
    roleIds: [{ required: true, message: '用户角色不能为空', trigger: 'blur' }],
    email: [
        {
            pattern: /\w[-\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,14}/,
            message: '请输入正确的邮箱地址',
            trigger: 'blur',
        },
    ],
    mobile: [
        {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: '请输入正确的手机号码',
            trigger: 'blur',
        },
    ],
})

const closeDialogCallback = () => {
    userFormRef.value!.resetFields()
}

const closeDialog = () => {
    dialog.visible = false
}

const openDialog = (userIdParam?: string) => {
    console.log('in openDialog userFormRef = ', userFormRef)
    dialog.visible = true
    userId = userIdParam
    // nextTick(() => {
    //     initForm()
    // })
}

const openDialogCallback = () => {
    initForm(userId)
}

async function initForm(userId?: string) {
    console.log('userId', userId)

    roleApi.getRoleOptions().then(({ data }) => {
        roleList.value = data
    })
    deptApi.getDeptOptions().then(({ data }) => {
        deptList.value = data
    })
    if (userId) {
        const { data } = await userApi.getUserForm(userId)
        formData.value = data
        dialog.title = '更新用户信息'
    } else {
        formData.value = cloneDeep(formDataIntial)
        console.log(' formDataIntial = ', formDataIntial)
        console.log(' formData.value = ', formData.value)

        dialog.title = '新增用户信息'
    }
    // console.log('userFormRef', userFormRef)
}

const handleSubmit = () => {
    userFormRef.value?.validate(async (valid) => {
        if (valid) {
            try {
                if (formData.value.id) {
                    await userApi.updateUser(formData.value.id, formData.value)
                    ElMessage.success('修改用户成功')
                } else {
                    await userApi.addUser(formData.value)
                    ElMessage.success('添加用户成功')
                }
                $bus.emit('user-table-query')
                closeDialog()
            } catch (error) {
                console.warn(error)
                ElMessage.warning(formData.value.id ? '修改用户失败' : '添加用户失败')
            }
        }
    })
}

defineExpose({
    openDialog,
})
</script>
<template>
    <el-dialog
        v-model="dialog.visible"
        :title="dialog.title"
        :width="dialog.width"
        :close-on-click-modal="false"
        @close="closeDialogCallback"
        @open="openDialogCallback"
    >
        <el-form ref="userFormRef" :model="formData" :rules="rules" label-width="80px">
            <el-form-item label="用户名" prop="username">
                <el-input
                    v-model="formData.username"
                    :readonly="!!formData.id"
                    placeholder="请输入用户名"
                />
            </el-form-item>

            <el-form-item label="用户昵称" prop="nickname">
                <el-input v-model="formData.nickname" placeholder="请输入用户昵称" />
            </el-form-item>

            <el-form-item label="所属部门" prop="deptId">
                <el-tree-select
                    v-model="formData.deptId"
                    placeholder="请选择所属部门"
                    :data="deptList"
                    filterable
                    check-strictly
                    :render-after-expand="false"
                />
            </el-form-item>

            <el-form-item label="性别" prop="gender">
                <EnumElSelectIndex v-model="formData.gender.value" :enumTypeLabel="EnumTypeLable.GenderEnumLabel" />
            </el-form-item>

            <el-form-item label="角色" prop="roleIds">
                <el-select v-model="formData.roleIds" multiple placeholder="请选择">
                    <el-option
                        v-for="item in roleList"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                    />
                </el-select>
            </el-form-item>

            <el-form-item label="手机号码" prop="mobile">
                <el-input v-model="formData.mobile" placeholder="请输入手机号码" maxlength="11" />
            </el-form-item>

            <el-form-item label="邮箱" prop="email">
                <el-input v-model="formData.email" placeholder="请输入邮箱" maxlength="50" />
            </el-form-item>

            <el-form-item label="状态" prop="status">
                <el-radio-group v-model="formData.status">
                    <el-radio :label="1">正常</el-radio>
                    <el-radio :label="0">禁用</el-radio>
                </el-radio-group>
            </el-form-item>
        </el-form>
        <!-- 弹窗底部操作按钮 -->
        <template #footer>
            <div class="dialog-footer">
                <el-button type="primary" @click="handleSubmit">确 定</el-button>
                <el-button @click="closeDialog">取 消</el-button>
            </div>
        </template>
        <p>
            {{formData  }} 
        </p>
    </el-dialog>

  
</template>
<style lang="scss" scoped></style>
